/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.refunite.mobile.s60.ui;

import org.refunite.mobile.s60.RefugeesUnited;
import org.refunite.mobile.s60.dto.CompletedFormData;
import org.refunite.mobile.s60.exception.TechnicalException;
import org.refunite.mobile.s60.persistence.PersistenceStoreProvider;
import org.refunite.mobile.s60.ws.WebServiceProvider;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import org.netbeans.microedition.lcdui.WaitScreen;
import org.netbeans.microedition.util.SimpleCancellableTask;

/**
 * @author I040022
 */
public class SendDataScreen implements CommandListener, ItemCommandListener {

    private RefugeesUnited midlet;
    private Alert couldNotSendAlert = new Alert("Could not send data to server", "Please check Server Settings", null, AlertType.ERROR);
    private Alert formSentAlert = new Alert("Info", "Collected Data sending finished", null, AlertType.INFO);

    private int numOfSavedForms = 0;

    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Form sendData;
    private StringItem stringItem;
    private StringItem sendDataItem;
    private WaitScreen sendDataWaitScreen;
    private Command backCommand;
    private Command sendDataCommand;
    private SimpleCancellableTask task;
    //</editor-fold>//GEN-END:|fields|0|

    /**
     * The SendDataScreen constructor.
     * @param midlet the midlet used for getting
     */
    public SendDataScreen (MIDlet midlet) {
        this.midlet = (RefugeesUnited)midlet;
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|2-switchDisplayable|0|2-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|2-switchDisplayable|0|2-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|2-switchDisplayable|1|2-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|2-switchDisplayable|1|2-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|2-switchDisplayable|2|
    //</editor-fold>//GEN-END:|2-switchDisplayable|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: sendData ">//GEN-BEGIN:|11-getter|0|11-preInit
    /**
     * Returns an initiliazed instance of sendData component.
     * @return the initialized component instance
     */
    public Form getSendData() {
        if (sendData == null) {//GEN-END:|11-getter|0|11-preInit
            // write pre-init user code here
            sendData = new Form("Send Data", new Item[] { getStringItem(), getSendDataItem() });//GEN-BEGIN:|11-getter|1|11-postInit
            sendData.addCommand(getBackCommand());
            sendData.setCommandListener(this);//GEN-END:|11-getter|1|11-postInit
            // write post-init user code here
        }//GEN-BEGIN:|11-getter|2|
        return sendData;
    }
    //</editor-fold>//GEN-END:|11-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: display ">//GEN-BEGIN:|12-entry|0|13-preAction
    /**
     * Performs an action assigned to the display entry-point.
     */
    public void display() {//GEN-END:|12-entry|0|13-preAction
        // write pre-action user code here
        switchDisplayable(null, getSendData());//GEN-LINE:|12-entry|1|13-postAction
        // write post-action user code here
        getNumberOfSavedForms();
    }//GEN-BEGIN:|12-entry|2|
    //</editor-fold>//GEN-END:|12-entry|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem ">//GEN-BEGIN:|15-getter|0|15-preInit
    /**
     * Returns an initiliazed instance of stringItem component.
     * @return the initialized component instance
     */
    public StringItem getStringItem() {
        if (stringItem == null) {//GEN-END:|15-getter|0|15-preInit
            // write pre-init user code here
            stringItem = new StringItem("Number Of Collected Forms:", null);//GEN-LINE:|15-getter|1|15-postInit
            // write post-init user code here
        }//GEN-BEGIN:|15-getter|2|
        return stringItem;
    }
    //</editor-fold>//GEN-END:|15-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|4-commandAction|0|4-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|4-commandAction|0|4-preCommandAction
        // write pre-action user code here
        if (displayable == sendData) {//GEN-BEGIN:|4-commandAction|1|18-preAction
            if (command == backCommand) {//GEN-END:|4-commandAction|1|18-preAction
                // write pre-action user code here
                this.midlet.backToMenu();//GEN-LINE:|4-commandAction|2|18-postAction
                // write post-action user code here
            }//GEN-BEGIN:|4-commandAction|3|33-preAction
        } else if (displayable == sendDataWaitScreen) {
            if (command == WaitScreen.FAILURE_COMMAND) {//GEN-END:|4-commandAction|3|33-preAction
                // write pre-action user code here
//GEN-LINE:|4-commandAction|4|33-postAction
                // write post-action user code here
            } else if (command == WaitScreen.SUCCESS_COMMAND) {//GEN-LINE:|4-commandAction|5|32-preAction
                // write pre-action user code here
//GEN-LINE:|4-commandAction|6|32-postAction
                // write post-action user code here
            }//GEN-BEGIN:|4-commandAction|7|4-postCommandAction
        }//GEN-END:|4-commandAction|7|4-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|4-commandAction|8|
    //</editor-fold>//GEN-END:|4-commandAction|8|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|17-getter|0|17-preInit
    /**
     * Returns an initiliazed instance of backCommand component.
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|17-getter|0|17-preInit
            // write pre-init user code here
            backCommand = new Command("Back", Command.BACK, 0);//GEN-LINE:|17-getter|1|17-postInit
            // write post-init user code here
        }//GEN-BEGIN:|17-getter|2|
        return backCommand;
    }
    //</editor-fold>//GEN-END:|17-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: sendDataItem ">//GEN-BEGIN:|20-getter|0|20-preInit
    /**
     * Returns an initiliazed instance of sendDataItem component.
     * @return the initialized component instance
     */
    public StringItem getSendDataItem() {
        if (sendDataItem == null) {//GEN-END:|20-getter|0|20-preInit
            // write pre-init user code here
            sendDataItem = new StringItem("", "Send Data", Item.BUTTON);//GEN-BEGIN:|20-getter|1|20-postInit
            sendDataItem.addCommand(getSendDataCommand());
            sendDataItem.setItemCommandListener(this);
            sendDataItem.setLayout(ImageItem.LAYOUT_CENTER | Item.LAYOUT_TOP | Item.LAYOUT_VCENTER | ImageItem.LAYOUT_NEWLINE_BEFORE | Item.LAYOUT_2);//GEN-END:|20-getter|1|20-postInit
            // write post-init user code here
        }//GEN-BEGIN:|20-getter|2|
        return sendDataItem;
    }
    //</editor-fold>//GEN-END:|20-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Items ">//GEN-BEGIN:|5-itemCommandAction|0|5-preItemCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular item.
     * @param command the Command that was invoked
     * @param displayable the Item where the command was invoked
     */
    public void commandAction(Command command, Item item) {//GEN-END:|5-itemCommandAction|0|5-preItemCommandAction
        // write pre-action user code here
        if (item == sendDataItem) {//GEN-BEGIN:|5-itemCommandAction|1|22-preAction
            if (command == sendDataCommand) {//GEN-END:|5-itemCommandAction|1|22-preAction
                // write pre-action user code here
                switchDisplayable(null, getSendDataWaitScreen());//GEN-LINE:|5-itemCommandAction|2|22-postAction
                // write post-action user code here
            }//GEN-BEGIN:|5-itemCommandAction|3|5-postItemCommandAction
        }//GEN-END:|5-itemCommandAction|3|5-postItemCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|5-itemCommandAction|4|
    //</editor-fold>//GEN-END:|5-itemCommandAction|4|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: sendDataCommand ">//GEN-BEGIN:|21-getter|0|21-preInit
    /**
     * Returns an initiliazed instance of sendDataCommand component.
     * @return the initialized component instance
     */
    public Command getSendDataCommand() {
        if (sendDataCommand == null) {//GEN-END:|21-getter|0|21-preInit
            // write pre-init user code here
            sendDataCommand = new Command("", Command.ITEM, 0);//GEN-LINE:|21-getter|1|21-postInit
            // write post-init user code here
        }//GEN-BEGIN:|21-getter|2|
        return sendDataCommand;
    }
    //</editor-fold>//GEN-END:|21-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: sendDataWaitScreen ">//GEN-BEGIN:|29-getter|0|29-preInit
    /**
     * Returns an initiliazed instance of sendDataWaitScreen component.
     * @return the initialized component instance
     */
    public WaitScreen getSendDataWaitScreen() {
        if (sendDataWaitScreen == null) {//GEN-END:|29-getter|0|29-preInit
            // write pre-init user code here
            sendDataWaitScreen = new WaitScreen(getDisplay());//GEN-BEGIN:|29-getter|1|29-postInit
            sendDataWaitScreen.setTitle("Send Data");
            sendDataWaitScreen.setCommandListener(this);
            sendDataWaitScreen.setFullScreenMode(true);
            sendDataWaitScreen.setText("Sending data...");
            sendDataWaitScreen.setTask(getTask());//GEN-END:|29-getter|1|29-postInit
            // write post-init user code here
        }//GEN-BEGIN:|29-getter|2|
        return sendDataWaitScreen;
    }
    //</editor-fold>//GEN-END:|29-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: task ">//GEN-BEGIN:|34-getter|0|34-preInit
    /**
     * Returns an initiliazed instance of task component.
     * @return the initialized component instance
     */
    public SimpleCancellableTask getTask() {
        if (task == null) {//GEN-END:|34-getter|0|34-preInit
            // write pre-init user code here
            task = new SimpleCancellableTask();//GEN-BEGIN:|34-getter|1|34-execute
            task.setExecutable(new org.netbeans.microedition.util.Executable() {
                public void execute() throws Exception {//GEN-END:|34-getter|1|34-execute
                    // write task-execution user code here
                    sendData();
                }//GEN-BEGIN:|34-getter|2|34-postInit
            });//GEN-END:|34-getter|2|34-postInit
            // write post-init user code here
        }//GEN-BEGIN:|34-getter|3|
        return task;
    }
    //</editor-fold>//GEN-END:|34-getter|3|





    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(midlet);
    }

    /**
     * Exits MIDlet.
     * Note you have to implement proper MIDlet destroying.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        // midlet.destroyApp(true);
        midlet.notifyDestroyed();
    }

    private void getNumberOfSavedForms(){
        this.numOfSavedForms = PersistenceStoreProvider.getNumOfCompletedRegistrationForms();
        getStringItem().setText(String.valueOf(numOfSavedForms));
        if(numOfSavedForms == 0){
            getSendDataItem().removeCommand(getSendDataCommand());
        }else{
            getSendDataItem().addCommand(getSendDataCommand());
        }
    }

    private void sendData(){
        // show progress bar while sending data
        Vector storedDataVector = PersistenceStoreProvider.getCompletedRegistrationForms();
        Enumeration dataEnum = storedDataVector.elements();
        boolean retValue = true;
        String boolean_true = "true";
        boolean successful = true;
        try{
            while(dataEnum.hasMoreElements() && retValue){
            CompletedFormData formData = (CompletedFormData)dataEnum.nextElement();
                String response = WebServiceProvider.callSaveRegistrationFormWS(formData.getContent());
                if(response.equals(boolean_true)){
                    retValue = true;
                }else{
                    retValue = false;
                }
                if(retValue){
                    // delete record
                    PersistenceStoreProvider.deleteCompletedRegistrationForm(formData.getRecordId());
                }
            }
        }catch(TechnicalException e){
            // could not send data, show error
            successful = false;
        }
        if(successful){
            showAlert(formSentAlert, sendData);
        }else{
            showAlert(couldNotSendAlert, sendData);
        }
        getNumberOfSavedForms();
        
    }

    private void showAlert(Alert a, Displayable display){
        switchDisplayable(a, display);
    }
}
